package com.czl.module_storehouse.activity.operation;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.activity.BaseActivity;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.scan.ScanActivity;
import com.czl.module_storehouse.adapter.SelectedProductAdapter;
import com.czl.module_storehouse.databinding.ActivitySelectedProductBinding;
import com.czl.module_storehouse.databinding.HeaderSelectedProductBinding;
import com.czl.module_storehouse.event.SelectedProductEvent;
import com.czl.module_storehouse.event.SelectedProductResultEvent;
import com.czl.module_storehouse.mvp.presenter.ProductPresenter;
import com.czl.module_storehouse.mvp.view.ProductView;
import com.czl.module_storehouse.utils.QrCodeRuleUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * @author by xubin,
 * @date on 2022/2/17.
 * PS: Not easy to write code, please indicate.
 */
public class SelectedProductActivity extends BaseActivity<ActivitySelectedProductBinding> implements ProductView {
    private HeaderSelectedProductBinding mHeaderBinding;
    private SelectedProductAdapter mAdapter;
    @InjectPresenter
    ProductPresenter mProductPresenter;
    private SortBean mSortBean;
    private List<ProductBean> mProductBeanList;

    protected final ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            activityResult -> {
                if (activityResult != null && activityResult.getData() != null) {
                    String result = activityResult.getData().getStringExtra(ScanActivity.RESULT);
                    getProductInfo(QrCodeRuleUtils.handleStorehouseProductResult(result));
                }
            });

    @Override
    protected ActivitySelectedProductBinding getBinding(LayoutInflater layoutInflater) {
        return ActivitySelectedProductBinding.inflate(layoutInflater);
    }

    @Override
    protected void loadData() {
        super.loadData();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mHeaderBinding = HeaderSelectedProductBinding.inflate(getLayoutInflater(), binding.layoutTop, true);
        mAdapter = new SelectedProductAdapter(R.layout.item_selected_product);
        binding.recyclerView.setAdapter(mAdapter);
        mHeaderBinding.textScanCode.setOnClickListener(v -> scan());
        binding.textAdd.setOnClickListener(v -> submit());

        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SelectedProductEvent event) {
        if (event == null || event.getSortBean() == null) {
            return;
        }
        mSortBean = event.getSortBean();
        String sortName = mSortBean.getSortName();
        Integer applyNum = mSortBean.getApplyNum();
        if (applyNum == null || applyNum == 0) {
            mHeaderBinding.tvTitle.setText(sortName);
        } else {
            String text = sortName + "（" + applyNum + "）";
            mHeaderBinding.tvTitle.setText(text);
        }

        List<ProductBean> productBeanList = mSortBean.getProductList();
        mAdapter.setList(productBeanList);
        mProductBeanList = event.getProductBeanList();
        String title = event.getTitle();
        if (title == null) {
            title = "";
        }
        mToolBinding.toolbarContentTitle.setText(getString(R.string.store_title_goods, title));
        mHeaderBinding.tvGoodsTitle.setText(getString(R.string.store_title_goods, title));
        mHeaderBinding.textScanCode.setText(getString(R.string.scan_title_goods, title));
    }

    private void scan() {
        //扫码
        List<ProductBean> data = mAdapter.getData();
        if (mSortBean == null) {
            return;
        }
        Integer applyNum = mSortBean.getApplyNum();
        if (applyNum != null && applyNum <= data.size()) {
            return;
        }
        mLauncher.launch(new Intent(getContext(), ScanActivity.class));
    }

    private void submit() {
        if (mAdapter != null) {
            List<ProductBean> data = mAdapter.getData();
            mSortBean.setProductList(data);
        }
        EventBus.getDefault().postSticky(new SelectedProductResultEvent());
        finish();
    }

    private void getProductInfo(int productId) {
        if (mProductPresenter != null) {
            mProductPresenter.getProductInfo(productId);
        }
    }

    private void getProductInfo(String productCode) {
        if (mProductPresenter != null) {
            mProductPresenter.getProductInfoByCode(productCode);
        }
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (ProductPresenter.TAG_PRODUCT_INFO_BY_CODE.equals(httpResponse.getRequestTag())) {
            ProductBean productBean = (ProductBean) httpResponse.getData();
            if (productBean == null || mSortBean == null) {
                return;
            }
            if (isDamageProducts(mSortBean, productBean)) {
                showToast("该物品已登记损坏");
                return;
            }
            if (!productBean.isSortProduct(mSortBean.getSortId())) {
                showToast("不是该分类下的物品");
                return;
            }
            if (productBean.getStorehouseLocatId() == null
                    || productBean.getStorehouseLocatId() == 0) {
                showToast("该物品不存在");
                return;
            }
            if (productBean.getStorehouseId() == null
                    || productBean.getStorehouseId() != SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_ID)) {
                showToast("不是该仓库物品");
                return;
            }
            if (mProductBeanList != null && !mProductBeanList.isEmpty()) {
                if (getProductBean(productBean, mProductBeanList) != null) {
                    showToast("该物品已添加");
                    return;
                }
            }
            if (getProductBean(productBean, mAdapter.getData()) == null) {
                productBean.setManufactureDate(null);
                mAdapter.addData(productBean);
            } else {
                showToast("该物品已添加");
            }
        }
    }

    public boolean isDamageProducts(SortBean sortBean, ProductBean productBean) {
        if (sortBean.getExcProductList() == null || sortBean.getExcProductList().isEmpty()) {
            return false;
        }
        for (ProductBean bean : sortBean.getExcProductList()) {
            if (bean.getProductId() == null) {
                continue;
            }
            if (bean.getProductId().equals(productBean.getProductId())) {
                return true;
            }
        }
        return false;
    }

    public ProductBean getProductBean(ProductBean productBean, List<ProductBean> list) {
        if (list == null) {
            return null;
        }
        for (ProductBean bean : list) {
            if (bean.getProductId() == null) {
                continue;
            }
            if (bean.getProductId().equals(productBean.getProductId())) {
                return bean;
            }
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHeaderBinding != null) {
            mHeaderBinding.unbind();
        }
    }
}
